package cn.micro.keep.accounts.mybatis;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

@Slf4j
public class UpdateBatchMethod extends AbstractMethod {

  /**
   * @param methodName 方法名
   * @since 3.5.0
   */
  protected UpdateBatchMethod(String methodName) {
    super(methodName);
  }

  @Override
  public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
    String sql = "<script><foreach collection=\"list\" item=\"item\" separator=\";\">update %s %s where %s=#{%s} %s</foreach></script>";
    String additional = tableInfo.isWithVersion() ? tableInfo.getVersionFieldInfo().getVersionOli("item", "item.") : "" + tableInfo.getLogicDeleteSql(true, true);
    String setSql = sqlSet(tableInfo.isWithLogicDelete(), false, tableInfo, false, "item", "item.");
    String sqlResult = String.format(sql, tableInfo.getTableName(), setSql, tableInfo.getKeyColumn(), "item." + tableInfo.getKeyProperty(), additional);
    log.debug("sqlResult----->{}", sqlResult);
    SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass);
    // 第三个参数必须和RootMapper的自定义方法名一致
    return this.addUpdateMappedStatement(mapperClass, modelClass, "updateBatch", sqlSource);
  }
}